import classNames from 'classnames';
import { HTMLAttributes, useEffect, useRef } from 'react';

import classes from './index.module.less';

type Props = {
  src: string;
  mode?: 'aspectFill' | 'aspectFit';
  loadLazy?: boolean;
} & HTMLAttributes<HTMLDivElement>;
const imageMap = new WeakMap<HTMLDivElement, string>();
const observer = new IntersectionObserver(
  (entries, observer) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        const lazyImage = entry.target as HTMLDivElement;
        lazyImage.style.backgroundImage = `url(${imageMap.get(lazyImage)})`;

        observer.unobserve(lazyImage);
      }
    });
  },
  {
    root: null,
    rootMargin: '0px',
    threshold: 0,
  }
);

const Image: React.FC<Props> = ({ src, style = {}, loadLazy, mode = 'aspectFit', ...props }) => {
  const wrap = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const div = wrap.current;
    if (loadLazy) {
      if (div) {
        imageMap.set(div, src);
        observer.observe(div);
      }
    }

    return () => {
      if (div) {
        observer.unobserve(div);
        imageMap.delete(div);
      }
    };
  }, [loadLazy, src]);
  if (!loadLazy) {
    style.backgroundImage = `url(${src})`;
  }
  return (
    <div
      ref={wrap}
      className={classNames(classes.wrap, classes[mode], props.className)}
      style={{ ...style }}
    />
  );
};

export default Image;
